package com.sunnada.edu.system.quartz.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.service.PubMethods;
import com.sunnada.edu.system.pub.util.Utils;

public class AttendanceMonitMethods {

	/**
	 * @param kqSet
	 *            System.out.println("班次对比【时间类型】：" + TIME_TYPE);
	 *            System.out.println("班次对比【学生类型】：" + STUDENT_TYPE);
	 *            System.out.println("班次对比【日期维度】：" + STARTDATE + "~" + ENDDATE);
	 *            System.out.println("有效打卡时间范围：" + TIMEPOINT);
	 *            System.out.println("迟到时间点：" + TIMESTAMP);
	 *            System.out.println("短信类型：" + MESSAGE_TYPE);
	 *            System.out.println("短信内容：" + MESSAGE_CONTENT);
	 * @throws Exception
	 */
	public void doKQ(HashMap<String, String> kqSet) throws Exception {
		if (checkKqSet(kqSet)) {
			List<HashMap<String, String>> cList = (List<HashMap<String, String>>) findSchoolId();// 学校list
			for (HashMap<String, String> cmap : cList) {
				String schoolId = cmap.get("SCHOOL_ID");
				String schoolName = cmap.get("SCHOOL_NAME");
				boolean isMakeUp = getAttendanceState(schoolId);// 特殊日期判断
				if (isMakeUp) {
					List<HashMap<String, String>> classList = (List<HashMap<String, String>>) findClasses(schoolId);// 班级list
					for (HashMap<String, String> classMap : classList) {
						// 本班学生某一类型（通读或走读）实时考勤情况
						kqSet.put("SCHOOL_ID", schoolId);
						String classId = classMap.get("GRADE_ID");
						kqSet.put("CLASS_ID", classId);
						String msgContent = statisticsKQ(kqSet);
						// 向该班级班主任发短信
						if (Utils.isNotNull(msgContent)) {
							kqSet.put("MSG", msgContent);
							sentMsgTo(kqSet);
						}
					}
				}
			}
		}
	}

	/**
	 * 
	 * 检查 路口参数有效性
	 * 
	 * @param kqSet
	 * @return
	 */
	public boolean checkKqSet(HashMap<String, String> kqSet) {
		String TIME_TYPE = kqSet.get("TIME_TYPE");
		String STUDENT_TYPE = kqSet.get("STUDENT_TYPE");
		String STARTDATE = kqSet.get("STARTDATE");
		String ENDDATE = kqSet.get("ENDDATE");
		String TIMEPOINT = kqSet.get("TIMEPOINT");
		String TIMESTAMP = kqSet.get("TIMESTAMP");// 验证是否迟到的时间戳
		String MESSAGE_TYPE = kqSet.get("MESSAGE_TYPE");
		String MESSAGE_CONTENT = kqSet.get("MESSAGE_CONTENT");
		System.out.println("班次对比【时间类型】：" + TIME_TYPE);
		System.out.println("班次对比【学生类型】：" + STUDENT_TYPE);
		System.out.println("班次对比【日期维度】：" + STARTDATE + "~" + ENDDATE);
		System.out.println("有效打卡时间范围：" + TIMEPOINT);
		System.out.println("迟到时间点：" + TIMESTAMP);
		System.out.println("短信类型：" + MESSAGE_TYPE);
		System.out.println("短信内容：" + MESSAGE_CONTENT);

		if (Utils.isNull(TIME_TYPE)) {
			return false;
		} else if (Utils.isNull(STARTDATE)) {
			return false;
		} else if (Utils.isNull(ENDDATE)) {
			return false;
		} else if (Utils.isNull(TIMEPOINT)) {
			return false;
		} else if (Utils.isNull(TIMESTAMP)) {
			return false;
		}
		/*************** 所有日期转成yyyymmddhh24miss格式 **************************/
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String now = sdf.format(date);
		String valbg = TIMEPOINT.split("-")[0];
		String valed = TIMEPOINT.split("-")[1];
		kqSet.put("VALBG", now + valbg.replace(":", ""));// 打卡点有效时段开始
		kqSet.put("VALED", now + valed.replace(":", ""));// 打卡点有效时段结束
		kqSet.put("STARTDATE", STARTDATE.replace("-", "") + "000000");
		kqSet.put("ENDDATE", ENDDATE.replace("-", "") + "235959");
		kqSet.put("TIMESTAMP", now + TIMESTAMP.replace(":", ""));// 判断迟到的时间戳
		/*************** 所有日期转成yyyymmddhh24miss格式 **************************/

		return true;
	}

	/**
	 * 发送短信
	 * 
	 * @param kqSet
	 */
	private void sentMsgTo(HashMap<String, String> kqSet) {
		HashMap<String, String> param = new HashMap<String, String>();
		String batchId = PubMethods.getBatchId();
		param.put("batchId", batchId);
		param.put("sendType", "3");
		String tel = getTeacherTel(kqSet);
		param.put("tel", tel);
		String schoolId = kqSet.get("SCHOOL_ID");
		param.put("schoolId", schoolId);
		param.put("loginId", "sys");
		String MSG = kqSet.get("MSG");
		param.put("content", MSG);
		param.put("state", "0");
		System.out.println("实时考勤短信" + param);
		// 没有班主任就不发短信
		if (Utils.isNotNull(tel)) {
			PubMethods.insertMessage(param);
		}

	}

	/**
	 * 获取班主任手机号
	 * 
	 * @param kqSet
	 * @return
	 */
	public String getTeacherTel(HashMap<String, String> kqSet) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String CLASS_ID = kqSet.get("CLASS_ID");
		String sql = "select s.PHONE from t_teachergrade t ,t_teacher s where t.user_id=s.teacher_id and t.class_id='" + CLASS_ID + "' and s.REC_STATUS!='2' ";
		List<HashMap<String, String>> teacherList = (List<HashMap<String, String>>) dao.selectList(sql);
		if (teacherList.size() > 0) {
			return teacherList.get(0).get("PHONE");
		}
		return "";
	}

	/**
	 * 一个班级的考勤情况短信内容
	 * 
	 * @param kqSet
	 * @return
	 */
	public String statisticsKQ(HashMap<String, String> kqSet) {
		StringBuilder result = new StringBuilder();
		List<HashMap<String, String>> list = null;
		String MESSAGE_TYPE = kqSet.get("MESSAGE_TYPE");
		String TIMEPOINT = kqSet.get("TIMEPOINT");
		String MESSAGE_CONTENT = kqSet.get("MESSAGE_CONTENT");
		String VALBG = kqSet.get("VALBG");
		String VALED = kqSet.get("VALED");
		if ("1".equals(MESSAGE_TYPE)) {
			list = getNoBrushData(kqSet);

		} else if ("2".equals(MESSAGE_TYPE)) {
			list = getLateData(kqSet);
		}
		int size = list.size();
		for (HashMap<String, String> student : list) {
			result.append(student.get("STUDENT_NAME") + ",");
		}
		
		if (size > 0) {
			String stus = result.toString();
			stus = stus.substring(0, stus.length() - 1);
			MESSAGE_CONTENT = MESSAGE_CONTENT.replace("考勤时段", TIMEPOINT).replace("数量", "" + size);
			MESSAGE_CONTENT = MESSAGE_CONTENT.replace("数量", "" + size);
			MESSAGE_CONTENT = MESSAGE_CONTENT.replace("学生姓名", stus);
		} else {
			MESSAGE_CONTENT = "";
		}

		return MESSAGE_CONTENT;
	}

	public List<?> findSchoolId() {
		PubDao dao = AppContext.getInstance().getPubDao();
		return dao.selectList("select * from T_SCHOOL t where t.REC_STATUS <> '2' order by t.rec_id desc");
	}

	public List<?> findClasses(String schoolId) {
		PubDao dao = AppContext.getInstance().getPubDao();
		return dao.selectList("select  t.* from T_GRADE t where SCHOOL_ID='" + schoolId + "' and REC_STATUS!='2' and GRADE_TYPE='2' ");
	}

	/**
	 * 未打卡
	 * 
	 * @param kqSet
	 * @return
	 */
	public List<HashMap<String, String>> getNoBrushData(HashMap<String, String> kqSet) {
		String STUDENT_TYPE = kqSet.get("STUDENT_TYPE");
		String CLASS_ID = kqSet.get("CLASS_ID");
		String TIME_TYPE = kqSet.get("TIME_TYPE");
		String STARTDATE = kqSet.get("STARTDATE");
		String ENDDATE = kqSet.get("ENDDATE");
		String VALBG = kqSet.get("VALBG");
		String VALED = kqSet.get("VALED");
		String TIMESTAMP = kqSet.get("TIMESTAMP");// 验证是否迟到的时间戳
		String MESSAGE_TYPE = kqSet.get("MESSAGE_TYPE");
		String MESSAGE_CONTENT = kqSet.get("MESSAGE_CONTENT");
		PubDao dao = AppContext.getInstance().getPubDao();
		StringBuilder sql = new StringBuilder();
		sql.append(" select STUDENT_ID, STUDENT_NAME, CLASS_ID ");
		sql.append(" from T_STUDENT where  REC_STATUS!='2' ");
		// STUDENT_TYPE空值就是全部学生
		if (Utils.isNotNull(STUDENT_TYPE)) {
			sql.append(" and student_type = '" + STUDENT_TYPE + "' ");
		}
		sql.append(" and CLASS_ID = '" + CLASS_ID + "' ");
		sql.append(" and STUDENT_ID not in ");
		sql.append(" ( select distinct s.STUDENT_ID ");
		sql.append("  from T_CRD_DATA t, T_STUDENT s ");
		sql.append("  where t.PERSON_ID = s.student_id ");
		// STUDENT_TYPE空值就是全部学生
		if (Utils.isNotNull(STUDENT_TYPE)) {
			sql.append(" and student_type = '" + STUDENT_TYPE + "'  and  s.REC_STATUS!='2' ");
		}
		sql.append("  and s.CLASS_ID = '" + CLASS_ID + "'  ");
		sql.append(" and to_date(t.rec_time, 'yyyymmddhh24miss') >= to_date('" + STARTDATE + "', 'yyyymmddhh24miss') ");
		sql.append(" and to_date(t.rec_time, 'yyyymmddhh24miss') <= to_date('" + ENDDATE + "', 'yyyymmddhh24miss') ");
		sql.append("  and to_date(t.rec_time,'yyyymmddhh24miss') <= to_date('" + VALED + "','yyyymmddhh24miss') ");
		sql.append("  and to_date(t.rec_time,'yyyymmddhh24miss') >= to_date('" + VALBG + "','yyyymmddhh24miss')) ");
		return (List<HashMap<String, String>>) dao.selectList(sql.toString());
	}

	/**
	 * 迟到
	 * 
	 * @param kqSet
	 * @return
	 */
	public List<HashMap<String, String>> getLateData(HashMap<String, String> kqSet) {
		String STUDENT_TYPE = kqSet.get("STUDENT_TYPE");
		String CLASS_ID = kqSet.get("CLASS_ID");
		String TIME_TYPE = kqSet.get("TIME_TYPE");
		String STARTDATE = kqSet.get("STARTDATE");
		String ENDDATE = kqSet.get("ENDDATE");
		String VALBG = kqSet.get("VALBG");
		String VALED = kqSet.get("VALED");
		String TIMESTAMP = kqSet.get("TIMESTAMP");// 验证是否迟到的时间戳
		String MESSAGE_TYPE = kqSet.get("MESSAGE_TYPE");
		String MESSAGE_CONTENT = kqSet.get("MESSAGE_CONTENT");

		PubDao dao = AppContext.getInstance().getPubDao();
		StringBuilder sql = new StringBuilder();
		sql.append(" select s.STUDENT_ID, s.STUDENT_NAME, s.CLASS_ID ");
		sql.append("    from (select s.STUDENT_ID, s.STUDENT_NAME, s.CLASS_ID, t.rec_time ");
		sql.append(" from T_CRD_DATA t, T_STUDENT s ");
		sql.append(" where t.PERSON_ID = s.student_id ");
		// STUDENT_TYPE空值就是全部学生
		if (Utils.isNotNull(STUDENT_TYPE)) {
			sql.append(" and student_type = '" + STUDENT_TYPE + "'   and s.rec_status!='2' ");
		}
		sql.append(" and s.CLASS_ID = '" + CLASS_ID + "' ");
		sql.append(" and to_date(t.rec_time, 'yyyymmddhh24miss') >= to_date('" + STARTDATE + "', 'yyyymmddhh24miss') ");
		sql.append(" and to_date(t.rec_time, 'yyyymmddhh24miss') <= to_date('" + ENDDATE + "', 'yyyymmddhh24miss') ");
		sql.append("  and to_date(t.rec_time,'yyyymmddhh24miss') <= to_date('" + VALED + "','yyyymmddhh24miss') ");
		sql.append("  and to_date(t.rec_time,'yyyymmddhh24miss') >= to_date('" + VALBG + "','yyyymmddhh24miss') ");

		/******************* 打卡记录中最早或最晚begin ******************/
		sql.append(" and NOT EXISTS ");
		sql.append(" (select 1 ");
		sql.append(" from (select t.* ");
		sql.append(" from T_CRD_DATA t, T_STUDENT s ");
		sql.append(" where t.PERSON_ID = s.student_id ");
		// STUDENT_TYPE空值就是全部学生
		if (Utils.isNotNull(STUDENT_TYPE)) {
			sql.append(" and student_type = '" + STUDENT_TYPE + "'   and s.rec_status!='2' ");
		}
		sql.append(" and s.CLASS_ID = '" + CLASS_ID + "' ");
		sql.append(" and to_date(t.rec_time, 'yyyymmddhh24miss') >= to_date('" + STARTDATE + "', 'yyyymmddhh24miss') ");
		sql.append(" and to_date(t.rec_time, 'yyyymmddhh24miss') <= to_date('" + ENDDATE + "', 'yyyymmddhh24miss') ");
		sql.append("  and to_date(t.rec_time,'yyyymmddhh24miss') <= to_date('" + VALED + "','yyyymmddhh24miss') ");
		sql.append("  and to_date(t.rec_time,'yyyymmddhh24miss') >= to_date('" + VALBG + "','yyyymmddhh24miss')) tmp ");
		sql.append(" WHERE tmp.PERSON_ID = t.PERSON_ID ");
		if (TIME_TYPE.contains("ON")) {
			sql.append("   AND tmp.rec_time < t.rec_time) ) s ");
		} else {
			sql.append("   AND tmp.rec_time > t.rec_time) ) s ");
		}
		/******************* 打卡记录中最早或最晚end ******************/

		sql.append(" where to_date(s.rec_time, 'yyyymmddhh24miss') > to_date('" + TIMESTAMP + "', 'yyyymmddhh24miss') ");

		return (List<HashMap<String, String>>) dao.selectList(sql.toString());

	}

	public boolean getAttendanceState(String schoolId) throws Exception {
		String todayData = getTodayData();
		boolean isWeekend = isWeekend(todayData);
		boolean isMakeUp = !isWeekend;//不是周末
		PubDao dao = AppContext.getInstance().getPubDao();
		String lsql = "select t.TIMETYPE from T_ATTENDANCEDATESET t where t.school_id='" + schoolId + "' " + "and t.rec_status<>'2' "
				+ "and to_date(t.BEGIN_TIME,'yyyy-mm-dd') <= to_date('" + todayData + "','yyyy-mm-dd') "
				+ "and to_date(t.END_TIME,'yyyy-mm-dd') >= to_date('" + todayData + "','yyyy-mm-dd') ";
		List<?> aList = dao.selectList(lsql);
		int aInt = aList.size();
		if (aInt > 0) {
			HashMap<String, String> rmap = (HashMap<String, String>) aList.get(0);
			String TIMETYPE = rmap.get("TIMETYPE");
			if("1".equals(TIMETYPE)){
				isMakeUp=false;
			}else if("2".equals(TIMETYPE)){
				isMakeUp=false;
			}else if ("3".equals(TIMETYPE)) {
				isMakeUp = true;
			} else if ("4".equals(TIMETYPE)&&isWeekend) {
				isMakeUp = true;
			}
		}
		return isMakeUp;

	}

	// 获取今天日期
	public String getTodayData() {
		Date dNow = new Date(); // 当前时间
		Date dBefore = new Date();

		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(dNow);// 把当前时间赋给日历
		// calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
		dBefore = calendar.getTime(); // 得到前一天的时间

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
		String defaultStartDate = sdf.format(dBefore);
		return defaultStartDate;
	}

	public String getWeek(String s) throws Exception {
		String dayNames[] = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
		SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date date = new Date();
		try {
			date = sdfInput.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calendar.setTime(date);
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (dayOfWeek < 0)
			dayOfWeek = 0;

		// System.out.println(dayNames[dayOfWeek]);

		return dayNames[dayOfWeek];
	}

	private boolean isWeekend(String todayData) throws Exception {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date bdate = null;
		try {
			bdate = format.parse(todayData);
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(bdate);
		if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			return true;
		} else {
			return false;
		}
	}

	public static void main(String[] args) throws Exception {
		AttendanceMonitMethods test = new AttendanceMonitMethods();
		HashMap<String, String> kqSet = new HashMap<String, String>();
		kqSet.put("TIMEPOINT", "06:30:00-08:00:00");// 打卡点有效时段开始
		kqSet.put("STARTDATE", "2016-06-01");
		kqSet.put("ENDDATE", "2016-11-01");
		kqSet.put("TIMESTAMP", "07:00:00");
		test.checkKqSet(kqSet);
		System.out.println(kqSet);
	}

}
